<template>
  <div id="apiJsonCode" class="w-full h-120 bd" style="overflow: auto">
    <code-mirror v-model="codeVal" basic :lang="lang" class="w-full h-120 bd" />
  </div>
</template>

<script lang="ts" setup>
import CodeMirror from 'vue-codemirror6';
import { json } from '@codemirror/lang-json';

const props = defineProps({
  code: {
    type: String,
    default: ''
  }
});

watch(
  [() => props.code],
  ([code]) => {
    if (code) {
      codeVal.value = JSON.stringify(code, null, '\t');
    }
  },
  { deep: true }
);

// 初始化
let codeVal = ref('');
// 转成json字符串并格式化
if (props.code) {
  codeVal.value = JSON.stringify(props.code, null, '\t');
}
// json
const lang = json();

// 获取数据
const getData = () => {
  const str = codeVal.value?.toString();
  return str;
};

defineExpose({
  getData
});
</script>

<style lang="scss">
.cm-editor {
  height: 100%;
}
</style>
